// pages/visit/components/imgWarp/index.js
const app = getApp()
Component({

  /**
   * 组件的属性列表
   */
  properties: {
    item: {
      type: Object,
      value: {}
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    percent: 0,
    imgUrl: "",
    showProgress: false,
    opacity: 0,
    imgWidth: 0,
    imgHeight: 110
  },
  lifetimes: {
    attached() {
      const item = this.properties.item
      let imgUrl,showProgress = false,opacity = 0
      if(item.file) {
        imgUrl = item.file
        showProgress = true
        opacity = 1
        this.uploadImage(item.file)
      }else {
        imgUrl = app.setPath(item.content) 
      }
      this.setData({
        imgUrl,
        showProgress,
        opacity
      })
    }
  },
  /**
   * 组件的方法列表
   */  
  methods: {
    onLoad(e) {
      const {width,height} = e.detail
      const imgWidth = Math.round((this.data.imgHeight * width) /  height)
      this.setData({
        opacity: 1,
        imgWidth
      })
    },

    onError(e) {
      this.setData({
        imgUrl: "/assets/image/加载失败.png"
      })
    },

    onPreview() {
      wx.previewImage({
        urls: [this.data.imgUrl],
        current: this.data.imgUrl,
        success: () => {
          app.setWsIsClose(false)
        }
      })
    },
    uploadImage(filePath) {
      const uploadTask = wx.uploadFile({
        url: app.globalData.$baseUrl + "/api/common/uploadImg",
        filePath,
        name: "file",
        header: {
          'Authorization': "Bearer " + wx.getStorageSync('token'),
        },
        success: (res) => {
          uploadTask.offProgressUpdate()
          const data = JSON.parse(res.data)
          if(data.code === 200){
            const parmas = {...this.properties.item,file: undefined,content: data.data.path}
            app.ws.send(parmas,()=>{
              this.setData({
                showProgress: false
              })
            })
          }
        }
      })

      uploadTask.onProgressUpdate((res)=>{
        this.setData({
          percent: res.progress
        })
      })
    }
  },

})